package com.atom.module.mvvm.adapter

import android.annotation.SuppressLint
import android.view.MotionEvent
import android.view.View
import androidx.databinding.BindingAdapter
import com.atom.module.mvvm.livedata.SingleLiveData

/**
 * View上布局文件的参数进行适配
 * 当展示在布局前,系统会根据布局文件的每个View的自定义参数,来寻找自定义参数对应的适配器
 */
object ViewAttrAdapter {
    /**
     * 点击事件适配器,该参数和View的OnClick不冲突,该参数的优先级低于OnClick的优先级
     * 点击事件的适配器,能够对此进行监听
     */
    @BindingAdapter(value = ["event_on_click"], requireAll = true)
    @JvmStatic
    fun eventOnClick(v: View, event: ClickEvent<*>) {
        v.setOnClickListener {
            event.invoke(v)
            event.notifyChange()
        }
    }

    /**
     * onLongClick的适配,能够进行被观察的
     */
    @BindingAdapter(value = ["event_on_long_click"], requireAll = true)
    @JvmStatic
    fun eventOnLongClick(v: View, event: ClickEvent<Boolean>) {
        v.setOnLongClickListener {
            val invoke = event.invoke(v)
            event.notifyChange()
            invoke
        }
    }

    /**
     * touch监听,同样能够被观察,同时观察的数据时此时的Touch事件
     */
    @SuppressLint("ClickableViewAccessibility")
    @BindingAdapter(value = ["event_on_touch"], requireAll = true)
    @JvmStatic
    fun eventOnTouchEvent(v: View, event: TouchEvent<Boolean>) {
        v.setOnTouchListener { view, motionEvent ->
            val invoke = event.invoke(TouchEvent.TouchEventPack(view, motionEvent))
            event.notifyPropertyChanged(motionEvent.action)
            invoke
        }
    }

    /**
     * View的显示和隐藏,同样能够支持被观察.和预设值
     */
    @BindingAdapter(value = ["event_visit"], requireAll = true)
    @JvmStatic
    fun showHide(v: View, event: VisitEvent) {
        val oldVisibility = event.invoke(v);
        val newVisibility = when (event.get()) {
            View.GONE -> View.GONE
            View.VISIBLE -> View.VISIBLE
            View.INVISIBLE -> View.INVISIBLE
            else -> View.GONE
        }
        if (oldVisibility != newVisibility) {
            v.visibility = newVisibility
            event.notifyPropertyChanged(v.visibility)
        }
    }
}